package com.study.talk.ui.app.home.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.study.talk.databinding.FragmentHomeBinding
import com.study.talk.data.model.ChatCache
import com.study.common.DateUtil
import com.study.talk.ui.adapter.chat.ChatCachesAdapter
import com.study.talk.ui.app.base.BaseActivity
import com.study.talk.ui.app.base.BaseFragment
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class HomeFragment : BaseFragment() {

    private lateinit var binding: FragmentHomeBinding
    private val vm: HomeFragmentViewModel by viewModels()

    private val adapter: ChatCachesAdapter by lazy {
        ChatCachesAdapter(requireActivity() as BaseActivity)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        binding.homeListView.itemAnimator = null
        binding.homeListView.layoutManager = LinearLayoutManager(requireContext())
        binding.homeListView.adapter = adapter
        /** 加载本地会话列表 */
        vm.loadCaches().observe(viewLifecycleOwner) {
            if (it.isEmpty()) {
                binding.homeListView.visibility = View.GONE
                binding.cacheEmptyView.visibility = View.VISIBLE
            } else {
                binding.homeListView.visibility = View.VISIBLE
                binding.cacheEmptyView.visibility = View.GONE
                it.sortWith { a: ChatCache, b: ChatCache ->
                    val bTime = DateUtil.format.parse(b.createTime.replace("T".toRegex(), " "))
                        ?: throw RuntimeException("date format error!")
                    val aTime = DateUtil.format.parse(a.createTime.replace("T".toRegex(), " "))
                        ?: throw RuntimeException("date format error!")
                    return@sortWith bTime.compareTo(aTime)
                }
                adapter.submitList(it)
            }
        }
        return binding.root
    }
}